package com.lzw.security.handler;

import com.fasterxml.jackson.databind.ObjectMapper;

import com.lzw.security.util.JwtTokenUtil;
import com.lzw.security.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassNmae TidcAuthenticationSuccessHandler
 * @Description TODO
 * @Author 14631
 **/
@Component
public class TidcAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {

	@Autowired
    ObjectMapper objectMapper;
	@Autowired
	RedisUtil redisUtil;
	protected String getCredentialsCharset(HttpServletRequest httpRequest) {
		return "UTF-8";
	}
	@Override
	public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
		//authentication接口 封装了用户的认证信息 比如ip session UserDetails 如果登录的方式不一样里面的内容也会变化
		//这个接口如果传给前端里面的密码等内容会被隐藏
//		if(securityProperties.getLogin().getLoginType().equals(LoginType.JSSON)){
//			//这里可以使用自己的处理方法
//		}else{
//			//调用父类的处理方法也就是调用默认的处理方法 也就是跳转到用户本身请求的页面
//			super.onAuthenticationSuccess(httpServletRequest,httpServletResponse,authentication);
//		}

		String openId = authentication.getName();

		String token = (String) redisUtil.get(openId);
		if(token==null){
			token = JwtTokenUtil.generateToken(openId);// 登录成功处理器做
			redisUtil.set(token,openId); //存储两个小时
			redisUtil.set(openId,token); //存储两个小时
		}

		Map<String, Object> map = new HashMap<>();
		map.put("code", "201");
		if (authentication.getName()!=null) {
			map.put("code", "200");
		}
		Map<String,String> data = new HashMap<>();
		data.put("token",token);
		map.put("data",data);
		map.put("message", "登录成功");
		System.out.println("token"+token);
//		如果这个登录的配置返回方式是Json就使用我们自己写的返回Json的方式
		httpServletResponse.setContentType("application/json;charset=UTF-8");
		httpServletResponse.getWriter().write(objectMapper.writeValueAsString(map));


//		}
	}
}